package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.TextLeftRightAdapter;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.AuthStateUtils;
import com.cardbaobao.cardbabyclient.ui.dialog.AuthCodeImageDialog;
import com.cardbaobao.cardbabyclient.model.ShowText;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.SoftKeyboardUtils;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.ViewUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 9:06.
 * 学历查询
 */
public class AcademicInquiryActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.et_account)
    EditText etAccount;//账号

    @BindView(R.id.et_pwd)
    EditText etPwd;//密码

    @BindView(R.id.bt_ensure_commit)
    Button btEnsureCommit;//确认提交

    private String userName;
    private String userPwd;
    private String taskId;

    private AuthCodeImageDialog authCodeImageDialog;

    @Override
    protected void onResume() {
        super.onResume();
        GoogleAnalyticsUtil.setScreenName(Google.LEARN_QUERY);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId= Self.Page.app_educational_background_inquiry_page;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_academic_inquiry;
    }

    @OnClick({R.id.tv_agreement,R.id.bt_ensure_commit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_agreement:
                initIntent();
                SelfUtils.buriedClickData(Self.Action.app_click_chsi_inquiry_agreement,
                        Self.Action.app_click_chsi_inquiry_agreement_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S,
                        "学信网查询服务协议");
                mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S,
                        URLUtil.DATA_PARSER_AGREEMENT);
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 5);
                startActivity(mIntent);
                break;
            case R.id.bt_ensure_commit:
                //确认提交
                SoftKeyboardUtils.hideSoftKeyboard(getCurrentFocus());
                if (checkAccount() && checkPwd()) {
                    SelfUtils.buriedClickData(Self.Action.app_click_education_history_inquiry,
                            Self.Action.app_click_education_history_inquiry_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    userName = etAccount.getText().toString().trim();
                    userPwd = etPwd.getText().toString().trim();
                    preChsiAuth();
                    GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_SERVICE, Google.ACTION_LEARN_QUERY);
                }
                break;
        }
    }

    private boolean checkAccount() {
        boolean result = false;
        String account = etAccount.getText().toString().trim();
        if (account.length() > 0) {
            result = true;
        } else {
            ToastUtil.showToastOnScreenCenter("请输入账号");
        }
        return result;
    }

    private boolean checkPwd() {
        boolean result = false;
        String pwd = etPwd.getText().toString().trim();
        if (pwd.length() > 0) {
            result = true;
        } else {
            ToastUtil.showToastOnScreenCenter("请输入密码");
        }
        return result;
    }

    @OnCheckedChanged(value = {R.id.cb_agreement, R.id.cb_pwd_toggle})
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_pwd_toggle:
                if (isChecked) {
                    ViewUtil.toggleEditTextInputType(etPwd, false);
                } else {
                    ViewUtil.toggleEditTextInputType(etPwd, true);
                }
                try {
                    etPwd.setSelection(etPwd.getText().toString().trim().length());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.cb_agreement:
                if (isChecked) {
                    btEnsureCommit.setEnabled(true);
                } else {
                    btEnsureCommit.setEnabled(false);
                }
                break;
        }
    }

    private void showAuthCodeDialog(Bitmap bitmap) {
        if (authCodeImageDialog == null) {
            authCodeImageDialog = new AuthCodeImageDialog(mContext);
            authCodeImageDialog.setAuthImage(bitmap);
            authCodeImageDialog.setButtonClickedListener(new AuthCodeImageDialog.OnAuthCodeButtonClicked() {
                @Override
                public void onRefreshButtonClicked() {
                    preChsiAuth();
                }

                @Override
                public void onCommitButtonClicked(String authCode) {
                    chsiAuth(authCode);
                }
            });
            authCodeImageDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    authCodeImageDialog.callSoftKeyBoard();
                }
            });
            authCodeImageDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    SoftKeyboardUtils.hideSoftKeyboard(getCurrentFocus());
                }
            });
        } else {
            authCodeImageDialog.setAuthImage(bitmap);
        }
        authCodeImageDialog.clearText();
        if (!authCodeImageDialog.isShowing()) {
            authCodeImageDialog.show();
        }
    }

    private void dismissAuthCodeDialog() {
        if (authCodeImageDialog != null && authCodeImageDialog.isShowing()) {
            authCodeImageDialog.dismiss();
        }
    }

    /**
     * 学信网授权，获取验证码，任务id等
     */
    private void preChsiAuth() {
        showProgressDialog(false);
        Observable<String> observable=Api.preChsiAuth();
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json = JSON.parseObject(s);
                if (json.getIntValue("code") == 2005) {
                    //获取验证码成功
                    taskId = json.getString("task_id");
                    byte[] bytes = Base64.decode(json.getString("authCode"), Base64.DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    showAuthCodeDialog(bitmap);
                } else {
                    ToastUtil.showToast(json.getString("message"));
                }
            }
        });
    }

    /**
     * 学信网授权
     */
    private void chsiAuth(String authCode) {
        showProgressDialog(false);
        Map<String,Object> params=new HashMap<>();
        params.put("user_id", mApplication.getUser().getID());
        params.put("user_name", userName);
        params.put("user_pass", userPwd);
        params.put("task_id", taskId);
        params.put("auth_code", authCode);
        params.put("action", 0);
        Observable<String> observable=Api.chsiAuth(params);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json = JSON.parseObject(s);
                int code = json.getIntValue("code");
                if (AuthStateUtils.isSuccess(code)) {
                    //授权成功
                    dismissAuthCodeDialog();
                    JSONArray array = json.getJSONObject("data").getJSONArray("education_info");
                    if (array != null && array.size() > 0) {
                        ArrayList<ShowText> academics = new ArrayList<>();
                        JSONObject object;
                        for (int i = 0, size = array.size(); i < size; i++) {
                            object = array.getJSONObject(i);
                            if (object.containsKey("realname")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "姓名:", object.getString("realname")));
                            }
                            if (object.containsKey("birthday")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "生日:", object.getString("birthday")));
                            }
                            if (object.containsKey("gender")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "性别:", object.getString("gender")));
                            }
                            if (object.containsKey("certificate_id")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "证书编号:", object.getString("certificate_id")));
                            }
                            if (object.containsKey("school")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "毕业院校:", object.getString("school")));
                            }
                            if (object.containsKey("edu_level")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "学历层次:", object.getString("edu_level")));
                            }
                            if (object.containsKey("entrance_date")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "入学时间:", object.getString("entrance_date")));
                            }
                            if (object.containsKey("major")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "专业名称:", object.getString("major")));
                            }
                            if (object.containsKey("graduate_date")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "毕业时间:", object.getString("graduate_date")));
                            }
                            if (object.containsKey("edu_conclusion")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "毕结业结论:", object.getString("edu_conclusion")));
                            }
                            if (object.containsKey("edu_type")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "学历类型:", object.getString("edu_type")));
                            }
                            if (object.containsKey("edu_form")) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_ITEM, "学习形式:", object.getString("edu_form")));
                            }
                            if (i < size - 1) {
                                academics.add(new ShowText(TextLeftRightAdapter.TYPE_DIVIDER, "", ""));
                            }
                        }
                        if (academics.size() > 0) {
                            initIntent();
                            mIntent.setClass(mContext, AcademicResultActivity.class);
                            mIntent.putParcelableArrayListExtra("academics", academics);
                            mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                            startActivity(mIntent);
                            finish();
                        } else {
                            ToastUtil.showToast("暂时没有查到相关信息！");
                        }
                    } else {
                        ToastUtil.showToast("暂时没有查到相关信息！");
                    }
                } else {
                    ToastUtil.showToast(json.getString("message"));
                    if (code == 102) {
                        //验证码错误，重新获取验证码
                        preChsiAuth();
                    } else {
                        dismissAuthCodeDialog();
                    }
                }
            }
        });
    }
}
